package cate.game.server.rpc.dispatch;

import cp.solution.rpc.RpcMsgHead;
import cp.solution.rpc.listener.RpcRequestResponseListener;
import cp.solution.rpc.message.RpcMessage;
import cp.solution.rpc.message.RpcMessageIoType;
import cp.solution.rpc.message.RpcMessageReader;
import easy.java.practice.errorcode.EcException;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

@Slf4j
public class RpcRrDispatcher {

    protected Map<String, RpcRequestResponseListener> map = new HashMap<>();

    public void addListener(String path, RpcRequestResponseListener handler) {
        map.put(path, handler);
    }

    public byte[] dispatch(RpcMsgHead head, byte[] msgBody) {
        RpcRequestResponseListener listener = map.get(head.path());
        if(listener == null) {
            throw new EcException("缺少path="+head.path()+"的RequestResponse处理器");
        }
        RpcMessage message = listener.apply(head, msgBody);
        try {
            return message.getBytes(RpcMessageIoType.output);
        } catch (Exception e) {
            log.error("", e);
            throw new EcException(e);
        }
    }
}
